'''
Created on Oct 3, 2012

@author: Himanshu

'''
#from parsera import Parsers
#from classifiers import kNN
#from testing import LOOCV
from featureset import gesture
import csv
import os
import utils
import generators
import math
#import numpy as np
import cPickle as pickle

if __name__ == '__main__':
    "Parsing Data Files"
    
#    startDelay = 5
#    noGestures = 10
#    gestureInterval = 10
#    endAdjust = 0
#    dirList = os.listdir(os.getcwd()+'\phidgetData')
#    for fname in dirList:
#        parser = Parsers()
#        name = fname.split('.')[0]
#        print 'Processing gesture: ' + name
#        parser.parse(name, 5)
#        parser.buildPickles(name , noGestures , gestureInterval)
#
    "read all gestures into memory and assign them scores"
#   

    #MODIFYING HERE 
    gestSet = utils.readAllPickles()
    utils.modGestsPosVelEner(gestSet)
    
#    aX = []
#    aY = []
#    aZ = []
#    gX = []
#    gY = []
#    gZ = []
#    
#    fileName = 'Window_Open1'
#    with open(os.getcwd()+"/phidgetData//" + fileName + '.csv', 'r') as csvfile:
#        reader = csv.reader(csvfile, dialect = 'excel')
#        index = 0
#        for row in reader:
#            index += 1
#            if ((row[0] != '') and (row.__len__() == 8) and (index >= 630) and (index <= 1245)):
#                offset = int(row[0])    
#                aX.append(float(row[2]))
#                aY.append(float(row[3])) 
#                aZ.append(float(row[4])) 
#                gX.append(float(row[5])*math.pi/180)
#                gY.append(float(row[6])*math.pi/180) 
#                gZ.append(float(row[7])*math.pi/180)         
#    features = ([] , [aX] , [aY] , [aZ] , [gX] , [gY] , [gZ] , [])  
#    gest = gesture('test-Window-Open' , features)
#    gest.setStartAccel([[-0.35851 , -0.96817 , -0.14347]])
#    generators.removeGrav(gest)
#    print gest.netaZ[0]

    path = os.getcwd() + '\pickles-test'
    #CAN CHANGE GESTURE NAME HERE
    fileName = 'Window_Open_mod_Pos_Vel.pkl'
    pklFile = open(path + '\\' + fileName, 'rb')
    gestureNameFull = pickle.load(pklFile)
    noGestures = pickle.load(pklFile)
    gest = pickle.load(pklFile)
#    #NET ACCERLARATION
#    ax = gest.netaX
#    #VELOCITY - 0 FOR X , 1 FOR Y , 2 FOR Z
#    vx = gest.returnVelocities()[0]
#    #POSITION
#    px = gest.dX
#    e = gest.energy
#    print ax[1]
#    print vx[1]
#    print px[1]
#    print e[1]
    print gest.netaNorm[0]
    print gest.aNorm[0]
    #print gest.netaZ[1]
###   print gestSet['Window_Close'].returnaX()[2].__len__()
#    print 'Pickles read successfully, contents of gestSet: \n' , gestSet.keys()
#    print 'Now Smoothing...'
#    f = open(os.getcwd() + '/results1.txt', 'wb')
#    utils.correctNorms(gestSet)
##   print gestSet['Window_Close'].returnaX()[2].__len__()
#    smoothGesGauss(gestSet , 7 , 2)
#    print 'Done Smoothing, Now prepping classifier'
#    
#    #utils.modGestsPosVel(gestSet)
#    gestureNames = ['Orient', 'Slap', 'Triangle', 'Window_Open', 'Window_Close', 'Fire_On', 'Fire_Off', 'Throw_Money', 'Swing_Phone',
#                    'W', 'Tap_Phone', 'Multi_Finger_Snap', 'Flick_Air', 'Door_Open', 'Door_Close']
#    gestureScores = [0.703, 0.891, 0.632, 0.694, 0.382, 0.312, 0.657, 0.805, 0.885, 0.598, 0.162, 0.776, 0.688, 1, 0.678]
#    
#    i = 0
#    
#    for name in gestureNames:
#        gest = gestSet[name]
#        gest.setScore(gestureScores[i])
#        gestSet[name] = gest
#        i += 1
#
#
#    #print 'Training and test sets ready. Training set: \n' , trainingSet.keys() , '\n test set: '
#    #print testGestures.keys()
#    features = ['worldaNorm']
#    classifier = kNN(features)
##    q = 4
#    print 'Classifier ready'
#    test = LOOCV(gestSet)
#    allerr = test.experiment(classifier , f)
#    for err in allerr:
#        print err
#        f.write(str(err))
#        f.write("\n")
#    print "STARTING AVERAGE ERRORS"
#    f.write("STARTING AVERAGE ERRORS"+"\n")
#    for err in allerr:
#        sumi = 0
#        for entry in err:
#            sumi += math.fabs(entry)
#        avg = sumi/err.__len__()
#        print avg
#        f.write(str(avg))
#        f.write("\n")
#    f.close()
    
    
        
        #for testName in testGestures.keys():
#        print "-----------------RUNNING ", testName , " ------------------"
#        testInstances = testGestures[testName].returnaNorm()
#        sumi = 0
#        i = 0
#        for instance in testInstances:
#            score = classifier.classifyAll(instance)
#            print score
#            sumi += score
#            i +=1
#            p = 1.0*i/testInstances.__len__()
#            print p, " % done!"
#        avg = sumi/testInstances.__len__()
#        print "Estimated Score: ", avg
#        print "Real Score: ", testGestures[testName].returnScore()
#        print "Difference: ", avg - testGestures[testName].returnScore()
        
        #    testGestureNames = ['Window_Close', 'Door_Close' , 'Swing_Phone']
#    testGestures = {}
#    trainingSet = gestSet
#    for testName in testGestureNames:
#        T = gestSet[testName]
#        testGestures[testName] = T
#        del trainingSet[testName]
#    featureList = []
#    scoreList = []
#    for key in trainingSet.keys():
#        gesture = trainingSet[key]
#        featureList = featureList + gesture.returnaNorm()
#        for i in range (gesture.returnaNorm().__len__()):
#            scoreList.append(gesture.returnScore())
#    
##    "Classify"
##    #print scoreList
        